import axios from "axios";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { ListState } from "../../hooks/useFetchList";
import { Swiper, ProductCard, ActionBar, NavBar } from "react-vant";
import { formatSellCount } from "../../utils/formatSellCount";
import { useDispatch } from "react-redux";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  // 容器
  const [v, setV] = useState<ListState>({} as ListState);
  // 1. 获取动态路由参数
  const { id } = useParams();
  // 2. 请求数据
  const fetchDetail = async () => {
    const resp = await axios.get(`/api/list/${id}`);
    console.log(resp.data);
    setV(resp.data.data);
  };
  // 3. 副作用
  useEffect(() => {
    fetchDetail();
  }, []);

  if (!v.id) {
    return <div>数据加载中....</div>;
  }

  return (
    <div>
      {/* 头部导航 */}
      <NavBar title="详情" onClickLeft={() => navigate(-1)}></NavBar>
      {/* 轮播区域 */}
      <Swiper>
        {v.images.map((v, i) => {
          return (
            <Swiper.Item key={i}>
              <img src={v} alt="" style={{ width: "100%", height: 200 }} />
            </Swiper.Item>
          );
        })}
      </Swiper>
      {/* 展示商品信息 */}
      <div className="good-info">
        <ProductCard
          price={<span style={{ color: "red" }}>¥： {v.price.toFixed(2)}</span>}
          title={v.title}
          desc={v.desc}
          num={
            <span style={{ color: "red" }}>
              已售： {formatSellCount(v.sellCount)}
            </span>
          }
        ></ProductCard>

        {/* 底部动作栏 */}
        <ActionBar>
          <ActionBar.Button
            type="danger"
            onClick={() => dispatch({ type: "addCarList", payload: {
              ...v,
              count: 1,
              state: false
            } })}
          >
            加入购物车
          </ActionBar.Button>
        </ActionBar>
      </div>
    </div>
  );
};

export default Index;
